#include "DataTransmiter.h"
#include "ctkPluginContext.h"
#include <QDomDocument>
#include <QApplication>
#include <qDebug>

//���ݿ������ļ�
#define XML_DB_PATH "/config/database.xml"
DataTransmiter::DataTransmiter(ctkPluginContext* context)
{
	context->registerService<IDataTransmiter>(this);
	m_pContext = context;
	init_All();
}

DataTransmiter::~DataTransmiter()
{
	delete m_pInfoCarMgr;
	m_pInfoCarMgr = NULL;
}

void DataTransmiter::init_All()
{
	init_DB();
	init_New();
	init_Connections();
}

void DataTransmiter::init_New()
{
	m_pInfoCarMgr = new InfoCarMgr();
	m_pInfoCarMgr->start();
	m_pReceiveMgr = new ReceiveMgr(m_pDBMgr);
	m_pReceiveMgr->init(m_strConnectName);
	m_pReceiveMgr->start();
}

void DataTransmiter::init_Connections()
{
	connect(m_pReceiveMgr, &ReceiveMgr::upBytes, m_pInfoCarMgr, &InfoCarMgr::addSendBytes,Qt::DirectConnection);
	connect(m_pInfoCarMgr, &InfoCarMgr::receiveBytes, m_pReceiveMgr, &ReceiveMgr::addDownBytes, Qt::DirectConnection);
}

void DataTransmiter::startTransmit()
{

}

void DataTransmiter::openXml()
{

}


bool DataTransmiter::init_DB()
{
	if (m_pDBMgr == NULL)
	{
		try
		{
			ctkServiceReference refDBMgr = m_pContext->getServiceReference<IDataBaseMgr>();
			m_pDBMgr = qobject_cast<IDataBaseMgr*>(m_pContext->getService(refDBMgr));
		}
		catch (const ctkInvalidArgumentException& e)
		{
			qDebug() << e.what();
			return false;
		}
	}

	if (m_pDBMgr == NULL)
		return false;
	if (!initConnectDB())
	{
		return false;
	}
	return true;
}

bool DataTransmiter::initConnectDB()
{
	QString str_Path = QApplication::applicationDirPath() + XML_DB_PATH;
	QFile file(str_Path);
	if (!file.open(QFile::ReadOnly | QFile::Text))
	{
		qDebug() << "database.xml open error!";
		return false;
	}
	QDomDocument doc;
	if (!doc.setContent(&file))
	{
		qDebug() << "error:doc.setContent(&file)!";
		return false;
	}
	QDomElement root = doc.documentElement();
	QString strDBType = root.firstChildElement("database").text();
	QString strHost = root.firstChildElement("hostName").text();
	QString strDBName = root.firstChildElement("databaseName").text();
	QString strUser = root.firstChildElement("userName").text();
	QString strPassword = root.firstChildElement("password").text();
	int nPort = root.firstChildElement("port").text().toInt();
	QString strError;
	m_strConnectName = m_pDBMgr->initConnection(strError, strDBType, strDBName, strHost, strUser, strPassword, nPort);
	if (m_strConnectName.isEmpty())
		return false;
	return true;
}